// 文件上传配置接口
export interface FileUploadConfig {
  accept?: string; // 接受的文件类型，如 "image" 或 "all"
  maxSize?: number; // 最大文件大小（MB）
  maxCount?: number; // 最大文件数量
  uploadUrl?: string; // 上传接口地址
  listType?: "text" | "picture" | "picture-card"; // 显示类型
  tips?: string; // 上传提示信息
}

// 选项数据接口
export interface OptionItem {
  value: string;
  text: string;
}

// 表单字段配置接口
export interface FieldConfig {
  key: string;
  label: string;
  type: "input" | "textarea" | "picker" | "datetime" | "date" | "native-date" | "image-upload" | "file-upload" | "readonly" | "department-picker" | "text" | "autocomplete";
  placeholder: string;
  required?: boolean;
  inputType?: string;
  maxlength?: number;
  pattern?: string; // 正则表达式验证
  patternErrorMessage?: string; // 正则验证失败的错误信息
  options?: string[];
  optionsData?: OptionItem[]; // 选项数据
  fileConfig?: FileUploadConfig; // 文件上传配置
  readonly?: boolean; // 只读字段标识
  showInCreate?: boolean; // 是否在新增页面显示
  showInEdit?: boolean; // 是否在编辑页面显示
  showInDetails?: boolean; // 是否在详情页面显示
  popupTitle?: string; // 弹窗标题（用于department-picker类型）
  departmentData?: any[]; // 部门数据（用于department-picker类型）
  // 自动补全相关配置
  searchApi?: (query: string) => Promise<OptionItem[]>; // 自动补全搜索API
  minSearchLength?: number; // 最小搜索长度
  debounceTime?: number; // 防抖时间
  // 原生日期选择器相关属性
  startDate?: string; // 开始日期
  endDate?: string; // 结束日期
  dateFormat?: 'YYYY-MM-DD' | 'YYYY/MM/DD' | 'MM/DD/YYYY'; // 日期格式
  disabled?: boolean; // 是否禁用
  validation?: (
    value: any,
    formData?: any,
  ) => { valid: boolean; message: string } | true;
}

// 表单分组接口
export interface FormSection {
  key: string;
  title: string;
  fields: FieldConfig[];
}

// 换班申请单表单配置
export const shiftSwapFormConfig: Record<string, FieldConfig> = {
  // 单据信息
  billCode: {
    key: "billCode",
    label: "单据编号",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  billStatus: {
    key: "billStatus",
    label: "单据状态",
    type: "readonly",
    placeholder: "系统自动生成",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: true,
    showInDetails: true,
  },
  remark: {
    key: "remark",
    label: "备注",
    type: "textarea",
    placeholder: "请输入备注信息",
    required: false,
    maxlength: 200,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 基本信息
  personId: {
    key: "personId",
    label: "被换班人员",
    type: "autocomplete",
    placeholder: "请输入工号或姓名搜索",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false,
  },
  staffNo: {
    key: "staffNo",
    label: "员工工号",
    type: "readonly",
    placeholder: "选取人员后带入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  name: {
    key: "name",
    label: "员工姓名",
    type: "readonly",
    placeholder: "选取人员后带入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 换班申请信息
  startTime: {
    key: "startTime",
    label: "换班时间",
    type: "native-date",
    placeholder: "请选择换班时间",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    startDate: "1950-01-01",
    endDate: "2050-12-31",
    dateFormat: "YYYY-MM-DD",
  },
  reason: {
    key: "reason",
    label: "事由",
    type: "textarea",
    placeholder: "请输入换班事由",
    required: true,
    maxlength: 500,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 换班对象信息
  swapPersonId: {
    key: "swapPersonId",
    label: "换班人员",
    type: "autocomplete",
    placeholder: "请输入工号或姓名搜索",
    required: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: false,
  },
  swapStaffNo: {
    key: "swapStaffNo",
    label: "换班人工号",
    type: "readonly",
    placeholder: "选取人员后带入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  swapName: {
    key: "swapName",
    label: "换班人姓名",
    type: "readonly",
    placeholder: "选取人员后带入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  swapSchedule: {
    key: "swapSchedule",
    label: "换班人员排班记录",
    type: "picker",
    placeholder: "请选择换班人员排班记录",
    required: false,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
    options: [],
    optionsData: [],
  },

  // 工作信息
  orgName: {
    key: "orgName",
    label: "公司",
    type: "readonly",
    placeholder: "选取人员后带入",
    required: false,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },
  groupName: {
    key: "groupName",
    label: "所属部门",
    type: "readonly",
    placeholder: "选取人员后带入",
    required: true,
    readonly: true,
    showInCreate: true,
    showInEdit: true,
    showInDetails: true,
  },

  // 工作信息 - 隐藏字段，用于存储数据
  groupId: {
    key: "groupId",
    label: "所属部门ID",
    type: "input",
    placeholder: "部门ID",
    required: false,
    showInCreate: false,
    showInEdit: false,
    showInDetails: false,
    departmentData: [], // 部门数据，将在页面加载时动态填充
  },
  // 工作信息 - 隐藏字段，用于存储数据
  orgId: {
    key: "orgId",
    label: "公司ID",
    type: "input",
    placeholder: "公司ID",
    required: false,
    showInCreate: false,
    showInEdit: false,
    showInDetails: false,
  },

  group: {
    key: "group",
    label: "所属部门",
    type: "readonly",
    placeholder: "所属部门",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },

  // 详情页面专用字段
  workflowStatus: {
    key: "workflowStatus",
    label: "工作流状态",
    type: "readonly",
    placeholder: "工作流状态",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approver: {
    key: "approver",
    label: "审批人",
    type: "readonly",
    placeholder: "审批人",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
  approvalTime: {
    key: "approvalTime",
    label: "审批时间",
    type: "readonly",
    placeholder: "审批时间",
    required: false,
    readonly: true,
    showInCreate: false,
    showInEdit: false,
    showInDetails: true,
  },
};

// 表单分组配置（新增页和编辑页）
export const formSections: FormSection[] = [
  {
    key: "billInfo",
    title: "单据信息",
    fields: [
      shiftSwapFormConfig.billCode,
      shiftSwapFormConfig.remark,
    ],
  },
  {
    key: "swappedPersonInfo",
    title: "被换班人员信息",
    fields: [
      shiftSwapFormConfig.personId,
      shiftSwapFormConfig.staffNo,
      shiftSwapFormConfig.name,
    ],
  },
  {
    key: "swapPersonInfo",
    title: "换班人员信息",
    fields: [
      shiftSwapFormConfig.swapPersonId,
      shiftSwapFormConfig.swapStaffNo,
      shiftSwapFormConfig.swapName,
      shiftSwapFormConfig.swapSchedule,
    ],
  },
  {
    key: "shiftSwapInfo",
    title: "换班信息",
    fields: [
      shiftSwapFormConfig.startTime,
      shiftSwapFormConfig.reason,
    ],
  },
  {
    key: "workInfo",
    title: "工作信息",
    fields: [
      shiftSwapFormConfig.orgName,
      shiftSwapFormConfig.groupName,
      shiftSwapFormConfig.orgId,
      shiftSwapFormConfig.groupId,
    ],
  },
  {
    key: "detailsInfo",
    title: "",
    fields: [
      shiftSwapFormConfig.billStatus,
      shiftSwapFormConfig.workflowStatus,
      shiftSwapFormConfig.approver,
      shiftSwapFormConfig.approvalTime,
    ],
  },
];

// 详情页专用的分组配置
const detailsFormSections: FormSection[] = [
  {
    key: "billInfo",
    title: "单据信息",
    fields: [
      shiftSwapFormConfig.billCode,
      shiftSwapFormConfig.remark,
    ],
  },
  {
    key: "swappedPersonInfo",
    title: "被换班人员信息",
    fields: [
      shiftSwapFormConfig.personId,
      shiftSwapFormConfig.staffNo,
      shiftSwapFormConfig.name,
    ],
  },
  {
    key: "swapPersonInfo",
    title: "换班人员信息",
    fields: [
      shiftSwapFormConfig.swapStaffNo,
      shiftSwapFormConfig.swapName,
      shiftSwapFormConfig.swapSchedule,
    ],
  },
  {
    key: "shiftSwapInfo",
    title: "换班信息",
    fields: [
      shiftSwapFormConfig.startTime,
      shiftSwapFormConfig.reason,
    ],
  },
  {
    key: "processInfo",
    title: "流程信息",
    fields: [
      shiftSwapFormConfig.approver,
      shiftSwapFormConfig.approvalTime,
    ],
  },
  {
    key: "workInfo",
    title: "工作信息",
    fields: [
      shiftSwapFormConfig.orgName,
      shiftSwapFormConfig.groupName,
    ],
  },
  {
    key: "statusInfo",
    title: "状态信息",
    fields: [
      shiftSwapFormConfig.billStatus,
      shiftSwapFormConfig.workflowStatus,
    ],
  },
];

// 根据页面类型过滤表单分组
export const getFormSectionsByPageType = (pageType: 'create' | 'edit' | 'details'): FormSection[] => {
  // 详情页使用专门的分组配置
  if (pageType === 'details') {
    return detailsFormSections.map(section => ({
      ...section,
      fields: section.fields.filter(field => field.showInDetails !== false)
    })).filter(section => section.fields.length > 0);
  }

  // 新增和编辑页使用默认分组配置
  return formSections.map(section => ({
    ...section,
    fields: section.fields.filter(field => {
      if (pageType === 'create') {
        return field.showInCreate !== false;
      } else if (pageType === 'edit') {
        return field.showInEdit !== false;
      }
      return false;
    })
  })).filter(section => section.fields.length > 0);
};

// 表单验证函数
export const validateForm = (
  formData: Record<string, any>,
): { valid: boolean; errors: Record<string, string> } => {
  const errors: Record<string, string> = {};
  let valid = true;

  // 遍历所有字段配置
  Object.values(shiftSwapFormConfig).forEach((field) => {
    const value = formData[field.key];

    // 必填字段验证
    if (field.required && !value) {
      errors[field.key] = `请输入${field.label}`;
      valid = false;
      return;
    }

    // 正则表达式验证
    if (field.pattern && value) {
      const pattern = new RegExp(field.pattern);
      if (!pattern.test(value)) {
        errors[field.key] =
          field.patternErrorMessage || `${field.label}格式不正确`;
        valid = false;
        return;
      }
    }

    // 自定义验证
    if (field.validation && value !== undefined) {
      const result = field.validation(value, formData);
      if (result !== true) {
        errors[field.key] = result.message;
        valid = false;
        return;
      }
    }
  });

  return { valid, errors };
};

